using MintAnimation.Runtime.Components;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

namespace MintAnimation.Editor
{
    [CustomEditor(typeof(MintAnimator))]
    public class MintAnimatorEditor : UnityEditor.Editor
    {

        private ReorderableList    _reorderableList;
        private SerializedProperty _isAutoPlay;
        private SerializedProperty _isLoop;
        private SerializedProperty _mintConfig;

        private void OnEnable()
        {
            this._reorderableList = new ReorderableList(this.serializedObject, this.serializedObject.FindProperty("Anims"), true, true, true, true);
            this._isAutoPlay      = this.serializedObject.FindProperty("IsAutoPlay");
            this._isLoop          = this.serializedObject.FindProperty("IsLoop");
            this._mintConfig      = this.serializedObject.FindProperty("AnimConfig");
            this._reorderableList.drawElementCallback = (rect, index, active, focused) =>
            {
                SerializedProperty serializedProperty = this._reorderableList.serializedProperty.GetArrayElementAtIndex(index);
                this._reorderableList.elementHeight = EditorGUI.GetPropertyHeight(serializedProperty);
                EditorGUI.PropertyField(rect, serializedProperty);
            };
            this._reorderableList.drawHeaderCallback = rect => { GUI.Label(rect, "Animations"); };
            this._reorderableList.onRemoveCallback   = list => { ReorderableList.defaultBehaviours.DoRemoveButton(list); };
            this._reorderableList.onAddCallback = list =>
            {
                if (list.serializedProperty != null)
                {
                    list.serializedProperty.arraySize++;
                    list.index = list.serializedProperty.arraySize - 1;
                }
                else
                {
                    ReorderableList.defaultBehaviours.DoAddButton(list);
                }
            };
        }

        public override void OnInspectorGUI()
        {
            this.serializedObject.Update();
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PropertyField(this._isAutoPlay);
            EditorGUILayout.PropertyField(this._isLoop);
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.PropertyField(this._mintConfig);
            if (this._mintConfig.objectReferenceValue == null)
            {
                this._reorderableList.DoLayoutList();
            }

            this.serializedObject.ApplyModifiedProperties();
        }

    }
}